const Koa = require('koa');
const koaStaticCache = require('koa-static-cache');
const koaBody = require('koa-body');
const compose = require('koa-compose');
const config = require('./config/index');
const router = require('./router/index');
const { jwtRoute } = require('./middlewares/jwt');
const middlewares = require('./middlewares/index');
const utils = require('./common/utils');

const { loadEnv } = require('./common/utils');
loadEnv();
// console.log(process.env.MYSQL_USER);

const app = new Koa();

app.context.config = config;
app.context.utils = utils;

// const connection = (function () {
//   let instance = null;

//   return function () {
//     if (!instance) {
//       instance = model.connection;
//     }

//     return instance;
//   }
// })();
// app.context.db = connection();

// const model = require("./model/index");

// app.context.db = model.connection;
// app.context.db = model.connect;

// 错误监控
app.on('error', (err, ctx) => {
  if (ctx) {
    ctx.body = {
      code: 9999,
      data: {},
      msg: `${err.name}：${err.message}`
    };
  }
});


process.on('unhandledRejection', (reason, p) => {
  console.log('Promise: ', p, 'Reason: ', reason)
  // do something
})

/* 查询字符串解析到`ctx.request.query` */
app.use(koaBody({
  multipart: true,
  // formidable: {
  //   maxFileSize: 200 * 1024 * 1024    // 设置上传文件大小最大限制，默认2M
  // }
}));

// 挂载中间件
app.use(compose(middlewares));

/* 当token验证异常时候的处理，如token过期、token错误 */
app.use(async (ctx, next) => {
  return next().catch((err) => {
    switch (err.status) {
      case 401: // token验证失败
        ctx.status = 200;
        ctx.body = {
          code: 401,
          data: {},
          msg: err.originalError ? err.originalError.message : err.message
        }
        break;
      case 402: // 数据验证失败
        ctx.status = 200;
        ctx.body = {
          code: 402,
          data: {},
          msg: err.originalError ? err.originalError.message : err.message
        }
        break;
      default:
        throw err;
        break;
    }
    // if (err.status === 401) {
    //   ctx.status = 200;
    //   ctx.body = {
    //     code: 401,
    //     data: {},
    //     msg: err.originalError ? err.originalError.message : err.message
    //   }
    // } else {
    //   throw err;
    // }
  });
});

/* 路由权限控制 */
app.use(jwtRoute);

app.use(router.routes());

//只要有请求，则通过koaStaticCache进行处理
app.use(koaStaticCache(__dirname + `/static`, {
  // root:__dirname+`/static`,    //与上面的第一个参数效果一样
  prefix: '/public', //如果当前请求的url是以/public开始，则作为静态资源请求
  gzip: true,
  maxAge: 2000,
  dynamic: true
}));


app.listen(config.port, config.host, () => {
  console.log(`Server running on http://localhost:${config.port}`);
  console.log(process.env.NODE_ENV)
  console.log(process.cwd())
});